package com.coder520.sync_learning.demo;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.concurrent.TimeUnit;

public class WaitNotify {
	static boolean flag=true;
	static Object lockObject=new Object();
	public static void main(String[] args) throws InterruptedException {
		Thread waiThread=new Thread(new Wait(),"WaitThread");
		
		waiThread.start();
		
		TimeUnit.SECONDS.sleep(5);
		
		Thread notifyThread=new Thread(new Notify(),"notifyThread");
		
		notifyThread.start();
		
		
	}
	static class Wait implements Runnable{
		@Override
		public void run() {
			// TODO Auto-generated method stub
//			加锁 ，用头lock的monitor
			synchronized (lockObject) {
//				当条件不足的时候，继续wait，同时释放了lock
				while (flag) {
					try {
						System.out.println(Thread.currentThread()+"flag is true.wait "+new SimpleDateFormat("HH:mm:ss").format(new Date()));
						lockObject.wait();
					} catch (Exception e) {
						// TODO: handle exception
					}
				}
				
//				条件满足的时候，完成工作
				System.out.println(Thread.currentThread()+"flag is false ,running 	"+new SimpleDateFormat("HH:mm:ss").format(new Date()));
			}
		}
	}
	
	static class Notify implements Runnable{
		@Override
		public void run() {
			// TODO Auto-generated method stub
			synchronized (lockObject) {
//				获取lock的锁，然后进行了通知，通知时候不会释放lock的锁，直到当前的线程释放了lock之后，WaitThread才能够从wait方法返回
				System.out.println(Thread.currentThread()+"hold lock is notify "+new SimpleDateFormat("HH:mm:ss").format(new Date()));
				
				lockObject.notifyAll();
				flag=false;
				
				SleepUtils.second(5);
			}
			
			synchronized (lockObject) {
				System.out.println(Thread.currentThread()+"hold lock again sleep "+new SimpleDateFormat("HH:mm:ss").format(new Date()));
				
				SleepUtils.second(5);
			}
		}
	}
	
}
